package com.cskaoyan.servlet;


import com.cskaoyan.bean.PageData;
import com.cskaoyan.bean.PageParameter;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.common.CommonServlet;
import com.cskaoyan.model.MarketTopic;
import com.cskaoyan.service.TopicService;
import com.cskaoyan.service.impl.TopicServiceImpl;
import com.cskaoyan.utils.JacksonUtil;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/topic/*")
public class AdminTopicServlet extends CommonServlet {
    TopicService topicService=new TopicServiceImpl();

    public BaseRespVo create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        MarketTopic marketTopic = JacksonUtil.read(jsonStr, MarketTopic.class);

        topicService.create(marketTopic);

        return BaseRespVo.ok(null);
    }
    
     public BaseRespVo list(HttpServletRequest request, HttpServletResponse response) {
         Map<String, String[]> map = request.getParameterMap();
         PageParameter pageParameter = new PageParameter();
         try {
             BeanUtils.copyProperties(pageParameter, map);
             List<MarketTopic> topicList = topicService.getTopicListPaged(pageParameter, map);
             PageData data = PageData.list(topicList);
             return BaseRespVo.ok(data);
         } catch (IllegalAccessException | InvocationTargetException e) {
             throw new RuntimeException(e);
         }
     }

    public BaseRespVo update(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        MarketTopic marketTopic = JacksonUtil.read(jsonStr, MarketTopic.class);

        topicService.update(marketTopic);
        return BaseRespVo.ok(null);
    }

    public BaseRespVo delete(HttpServletRequest request,HttpServletResponse response) throws IOException {

        String jsonStr = request.getReader().readLine();
        MarketTopic marketTopic = JacksonUtil.read(jsonStr, MarketTopic.class);

        topicService.delete(marketTopic);
        return  BaseRespVo.ok(null);
    }
}
